package com.light.applet.oauth.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.light.applet.common.exception.oauth.WechatOauthException;
import com.light.applet.oauth.config.OauthConfig;
import com.light.applet.common.entity.Account;
import com.light.applet.oauth.service.AccountService;
import com.light.applet.oauth.service.WechatOauthService;
import com.light.wanting.account.api.AccountFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;


/**
 * @author 魏彪
 */
@Service
@Slf4j
public class WechatOauthServiceImpl implements WechatOauthService {

    @Autowired
    private AccountService accountService;

    @Autowired
    private OauthConfig oauthConfig;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return Account.builder().nickName(username).passWord(passwordEncoder.encode("123456")).build();
    }

    @Override
    public UserDetails loadUserByCode(String code) throws WechatOauthException {
        String url = String.format(oauthConfig.getWechat().getLoginUrl(),
                oauthConfig.getWechat().getAppId(),
                oauthConfig.getWechat().getAppSecret(),
                code);

        HttpResponse response = HttpUtil.createGet(url).execute();
        String content = response.body();
        response.close();

        if (ObjectUtils.isEmpty(content)) {
            throw new WechatOauthException("获取微信用户失败");
        }

        JSONObject wxResult = JSON.parseObject(content, JSONObject.class);

        if (wxResult.containsKey(oauthConfig.getWechat().getResultCodeKey())) {
            throw new WechatOauthException(wxResult.getString(oauthConfig.getWechat().getResultMsgKey()));
        }

        log.info("当前的微信返回: {}", wxResult);
        Account account = new Account();
        account.setOpenId(wxResult.getString("openid"));
        return accountService.register(account);
    }

}
